package org.cardcopier.file;

import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NameFormatter {
    
    private static final Logger LOGGER = Logger.getLogger(NameFormatter.class.getName());
    
    private final MessageFormat nameFormat;
    private final String namePattern;
    
    public NameFormatter(String namePattern) {
        this.namePattern = namePattern;
        this.nameFormat = convertToMessageFormat(namePattern);
    }
    
    private MessageFormat convertToMessageFormat(String namePattern) {
        // Look for a date pattern
        String nameFormat = namePattern;
        Pattern pattern = Pattern.compile("%d\\{([^\\}]*)\\}");
        Matcher matcher = pattern.matcher(nameFormat);
        nameFormat = matcher.replaceAll("{0,date,$1}");
        
        // Look for the job pattern
        pattern = Pattern.compile("%n");
        matcher = pattern.matcher(nameFormat);
        nameFormat = matcher.replaceAll("{1}");
        LOGGER.fine("Converted namePattern ["+ namePattern + "] into messageFormat ["+nameFormat+"]");
        return new MessageFormat(nameFormat);
    }
    
    public String formatName(Date date, String name) {
        return nameFormat.format(new Object[] { date, name });
    }
    
    public String getNamePattern() {
        return namePattern;
    }
    
}
